﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using GoodStuff.Heartbeat.Core;
using GoodStuff.Heartbeat.Core.Configuration;
using System.Xml;
using System.Reflection;

namespace GoodStuff.Heartbeat.Service
{
    partial class HeartbeatService : ServiceBase
    {
        Engine engine = null;
   
        public HeartbeatService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            eventLog1.WriteEntry("Service started");

            //load the configuration.
            XmlConfigurationLoader loader = new XmlConfigurationLoader();
            XmlDocument doc = new XmlDocument();

            Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            doc.Load("configuration.xml");

            Settings.components = loader.LoadConfiguration(doc);

            if (engine != null)
            {
                OnStop();
            }

            engine = new Engine(Settings.components);
            engine.OnError += new EventHandler<ExceptionEventArgs>(engine_OnError);
            engine.OnTrace += new EventHandler<TraceEventArgs>(engine_OnTrace);
            engine.Start();
        }

        void engine_OnTrace(object sender, TraceEventArgs e)
        {
            eventLog1.WriteEntry(e.Message, EventLogEntryType.Information);
        }

        void engine_OnError(object sender, ExceptionEventArgs e)
        {
            eventLog1.WriteEntry(e.Error.Message, EventLogEntryType.Error);
        }

        protected override void OnStop()
        {
            eventLog1.WriteEntry("Service stopped");

            if (engine != null)
            {
                engine.Stop();
                engine = null;
            }
        }       
    }
}
